package com.project.school_flate.util.wechat;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.project.school_flate.util.system.ComVariableUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import javax.annotation.PostConstruct;
import java.util.HashMap;
import java.util.Map;

@Component
public class UserUtil {
    @Autowired
    private RestTemplate restTemplate;

    private static UserUtil userUtil;

    //第四步创建一个初始化方法，用于注入实体类，使用 @PostConstruct
    @PostConstruct
    public void init(){
        userUtil = this;
        //第五步，调用你需要使用的mapper
        userUtil.restTemplate = this.restTemplate;
    }

    /**
     * 获取openid
     * @param code
     * @return
     */
    public static String getSessionKeyOrOpenId(String code){
        //微信端登录code
        String requestUrl = "https://api.weixin.qq.com/sns/jscode2session";
        Map<String,Object> requestUrlParam = new HashMap<>();
        requestUrlParam.put("appid", ComVariableUtil.getSystemValue("wx_appid"));//小程序appId
        requestUrlParam.put("secret", ComVariableUtil.getSystemValue("wx_secret"));
        requestUrlParam.put("js_code",code);//小程序端返回的code
//        requestUrlParam.put( "grant_type","authorization_code");//默认参数
        //发送post请求读取调用微信接口获取openid用户唯一标识
        JSONObject jsonObject = JSONObject.parseObject(HttpUtil.post(requestUrl,requestUrlParam));
        String strOpenid = jsonObject.getString("openid");
        return strOpenid;
    }

    /**
     * 解密获取手机号
     * @param
     * @return
     * @throws Exception
     */
    public static String getPhone(String code) throws Exception {
        // 获取token
        String token_url = String.format("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s", ComVariableUtil.getSystemValue("wx_appid"), ComVariableUtil.getSystemValue("wx_secret"));
        JSONObject token = JSON.parseObject(HttpUtil.get(token_url));
        // 使用前端code获取手机号码 参数为json格式
        String url = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=" + token.getString("access_token");
        Map<String, String> paramMap = new HashMap<>();
        paramMap.put("code", code);
        HttpHeaders headers = new HttpHeaders();
        HttpEntity<Map<String, String>> httpEntity = new HttpEntity<>(paramMap, headers);
        ResponseEntity<Object> response =  userUtil.restTemplate.postForEntity(url, httpEntity, Object.class);
        return response.getBody().toString();
    }
}
